﻿using HttpContent = Microsoft.AspNetCore.Http.HttpContext;

namespace Anley.DomainDrivenDesign.Contract.Helper;

/// <summary>
/// 主机帮助类
/// </summary>
public class HostHelper
    : IHostHelper
{
    // 获取客户端IP
    public string? GetClientIp(
        HttpContent httpContext)
    {
        var ip = httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
        if (string.IsNullOrEmpty(ip))
            ip = httpContext.Request.Headers["X-Forwarded-Proto"].FirstOrDefault();
        if (string.IsNullOrEmpty(ip))
        {
            var ipAddress = httpContext.Connection.RemoteIpAddress;
            if (!(ipAddress == null))
                ip = ipAddress.MapToIPv4().ToString();
        }
        return ip;
    }

    // 获取IP地区
    public string? GetIpRegion(
        string? ip)
    {
        if (string.IsNullOrWhiteSpace(ip))
            return null;
        var xdbPath = Path.Combine(Directory.GetCurrentDirectory(), "ip2region.xdb");
        var searcher = new Searcher(CachePolicy.File, xdbPath);
        return searcher.Search(ip);
    }
}